﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace T.FAS.Runtime.Metadata.Entity.MF
{
    public class ShapeConverter:JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(ShapeBase);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jsonObject = JObject.Load(reader);
            string shape = jsonObject["shape"]?.Value<string>();

            switch (shape)
            {
                case "edge":
                    return jsonObject.ToObject<Edge>(serializer);
                case "start-node":
                    return jsonObject.ToObject<StartNode>(serializer);
                case "code-node":
                    return jsonObject.ToObject<CodeNode>(serializer);
                case "end-node":
                    return jsonObject.ToObject<EndNode>(serializer);
                case "if-else-node":
                    return jsonObject.ToObject<IfElseNode>(serializer);
                case "cdo-node":
                    return jsonObject.ToObject<CdoNode>(serializer);
                case "llm-node":
                    return jsonObject.ToObject<LLMNode>(serializer);
                case "group-start-node":
                    return jsonObject.ToObject<IterationStartNode>(serializer);
                case "iteration-node":
                    return jsonObject.ToObject<IterationNode>(serializer);
                case "if-node":
                    return jsonObject.ToObject<IfNode>(serializer);
                case "dataquery-node":
                    return jsonObject.ToObject<DataQueryNode>(serializer);
                case "action-node":
                    return jsonObject.ToObject<ActionNode>(serializer);
                case "subflow-node":
                    return jsonObject.ToObject<WorkflowNode>(serializer);
                case "http-node":
                    return jsonObject.ToObject<WorkflowNode>(serializer);
                default:
                    throw new JsonSerializationException($"未知的形状类型: {shape}");
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }
    }
}
